<?php


namespace app\common\cachemodel;


use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class ZlcrAstrAccount extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr_astr_account';

    protected $cacheModel = 'astr_admin.astr_account';

    /**
     * 更新占星师账户信息
     * @param int $id
     * @param int $astrId
     * @param array $data
     * @return bool
     */
    public function updateData(int $id, int $astrId, array $data)
    {
        try
        {
            $this->where('id', $id)->update($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->rmCache();
        }
        catch (\Exception $e)
        {
            Log::write('更新占星师账户信息失败；账户ID【' . $id . '】;更新数据：' . json_encode($data, JSON_UNESCAPED_UNICODE) . ';错误信息:' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」");
            return false;
        }

        return true;
    }

    /**
     * 获取占星师账号信息
     * @param int $astrId
     * @param array $field
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getAstrAccountInfo(int $astrId, array $field = [])
    {
        // $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->getDataAndSet(function () use ($astrId)
        // {
        try
        {
            $data = $this->field('id,astr_id,status,balance,total_amount,withdraw_amount,last_withdraw_time,create_time')->where(['astr_id' => $astrId])->find();

            //若占星师没有账户数据则生成
            if (!$data)
            {
                $data = [
                    'astr_id' => $astrId,
                    'status' => 1,
                    'balance' => 0, // 余额
                    'total_amount' => 0,    // 累计收益
                    'withdraw_amount' => 0,
                    'last_withdraw_time' => 0,
                    'create_time' => time(),
                ];
                $data['id'] = $this->insertGetId($data);
                $data['month_earnings'] = 0; // 本月收益
                $data['last_month_earnings'] = 0; // 上月收益
            } else
            {
                $data = $data->toArray();
                // 统计 本月收益
                $data['month_earnings'] = $this->table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')
                    ->where(['astr_id' => $astrId, 'type' => 1, 'status' => 1])
                    ->whereTime('create_time', 'm')
                    ->sum('amount');
                // 统计 上月收益
                $data['last_month_earnings'] = $this->table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')
                    ->where(['astr_id' => $astrId, 'type' => 1, 'status' => 1])
                    ->whereTime('create_time', ['first Day of last month 00:00:00', 'first Day of this month 00:00:00'])
                    ->sum('amount');
            }
        }
        catch (\Exception $e)
        {
            Log::write('获取占星师账户信息失败；占星师ID【' . $astrId . '】;错误信息:' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」");
            $data = [];
        }

        //     return $data;
        // }, $field);

        return $data;
    }

    /**
     * 占星师 问答 收益发放
     * @param array $data
     *      [
     *          'earning' => 本单收益，扣除手续费及营业税费
     *          'total_amount' => 本单用户实际支付总金额 问题金额+所有追问支付金额（有效，取消的不算在内）
     *          'astr_id' => 占星师ID
     *          'type' => 1=>入账 2=>提现 3=>后台人员回复的用户内容 4=>问答冻结  5=>问答解冻
     *          'gid' => 问答问题ID  仅存问题ID
     *          'proportion' => 问答问题收益比例
     *          'question_type' => 1=>星盘 2=>骰子 3=>塔罗
     *          'qid' => 问答ID
     *          'team_id' => 团队ID
     *      ]
     * @return bool
     */
    public function astrQuestionAnswerEarningsSend(array $data)
    {
        try
        {
            // 获取占星师账户信息
            $astrAccountInfo = $this->getAstrAccountInfo($data['astr_id']);
            // 需要更新的占星师账户信息
            $accountData = [
                'balance' => (float)sprintf("%.2f", $astrAccountInfo['balance'] + $data['earning']),
                'total_amount' => (float)sprintf("%.2f", $astrAccountInfo['total_amount'] + $data['earning']),
                'update_time' => time(),
            ];
            Log::write('占星师账户 流水发放；发放前账户信息：' . json_encode($astrAccountInfo, JSON_UNESCAPED_UNICODE) . ';预更新信息' . json_encode($accountData, JSON_UNESCAPED_UNICODE), 'log', true);
            // 更新占星师账户信息
            // 占星师回复 更新占星师账户信息
            $this->updateData((int)$astrAccountInfo['id'], $data['astr_id'], $accountData);
            // 新增占星师能力值 1点    占星师行为=>占星师每完成一单，能力分+1
            (new ZlcrAstr())->changeAstrScore($data['astr_id'], $data['qid'], 1, $data['question_type'], 5, 0);
            // 新增占星师账户记录
            $accountRecord = [
                'astr_id' => $data['astr_id'],
                'type' => (int)$data['type'],
                'gid' => $data['gid'],
                'qid' => $data['qid'],
                'good_amount' => $data['total_amount'],
                'proportion' => $data['proportion'],
                'question_type' => 2,   // 1=>定制报告 2=>问答
                'amount' => $data['earning'],
                'balance' => $accountData['balance'],
                'create_time' => $accountData['update_time'],
                'team_id' => $data['team_id'],
            ];
            (new ZlcrAstrAccountRecord())->addRecord($data['astr_id'], $accountRecord);
        }
        catch (\Exception $e)
        {
            Log::write('占星师 问答 收益发放，错误信息:' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error');
            return false;
        }
        return true;
    }

    /**
     * RTC 连线咨询 收益发放
     * @param array $data
     *      [
     *          'earning' => 本单收益，扣除手续费及营业税费
     *          'total_amount' => 本单用户实际支付总金额 问题金额+所有追问支付金额（有效，取消的不算在内）
     *          'astr_id' => 占星师ID
     *          'type' => 1=>入账 2=>提现 3=>后台人员回复的用户内容 4=>问答冻结  5=>问答解冻
     *          'gid' => 问答问题ID  仅存问题ID
     *          'proportion' => 问答问题收益比例
     *          'service_duration' => 服务时长
     *          'team_id' => 团队ID
     *      ]
     * @param int $appType 1=>准有好事  2=>准了APP
     * @return bool
     */
    public function astrRtcConsultEarningsSend(array $data, int $appType = 1)
    {
        try
        {
            // 获取占星师账户信息
            $astrAccountInfo = $this->getAstrAccountInfo($data['astr_id']);
            // 需要更新的占星师账户信息
            $accountData = [
                'balance' => (float)sprintf("%.2f", $astrAccountInfo['balance'] + $data['earning']),
                'total_amount' => (float)sprintf("%.2f", $astrAccountInfo['total_amount'] + $data['earning']),
                'update_time' => time(),
            ];
//            Log::write('占星师账户 流水发放；发放前账户信息：' . json_encode($astrAccountInfo, JSON_UNESCAPED_UNICODE) . ';预更新信息' . json_encode($accountData, JSON_UNESCAPED_UNICODE), 'log', true);
            // 更新占星师账户信息
            // 占星师回复 更新占星师账户信息
            $this->updateData((int)$astrAccountInfo['id'], $data['astr_id'], $accountData);
            $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
            $update = [
                'service_num' => $this->raw('service_num + 1'),
                'service_duration' => $this->raw('service_duration + ' . $data['service_duration']),
            ];
            // 更新咨询师服务时长
            $zlcr3ConsultAccountModel->updateData($data['astr_id'], $update);
            // 新增占星师账户记录
            $accountRecord = [
                'astr_id' => $data['astr_id'],
                'type' => (int)$data['type'],
                'gid' => $data['gid'],
                'qid' => 0,
                'good_amount' => $data['total_amount'],
                'proportion' => $data['proportion'],
                'question_type' => $appType === 1 ? 3 : 5,   // 1=>定制报告 2=>问答 3=>准有好事-连线咨询 4=>准有好事-问答 5=>准了-连线咨询
                'amount' => $data['earning'],
                'balance' => $accountData['balance'],
                'create_time' => $accountData['update_time'],
                'team_id' => $data['team_id'],
            ];
            (new ZlcrAstrAccountRecord())->addRecord($data['astr_id'], $accountRecord);
        }
        catch (\Exception $e)
        {
            Log::write('占星师 问答 收益发放，错误信息:' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error');
            return false;
        }
        return true;
    }

    /**
     * 占星师 准有好事 - 问答 收益发放
     * @param array $data
     *      [
     *          'earning' => 本单收益，扣除手续费及营业税费
     *          'total_amount' => 本单用户实际支付总金额 问题金额+所有追问支付金额（有效，取消的不算在内）
     *          'astr_id' => 占星师ID
     *          'type' => 1=>入账 2=>提现 3=>后台人员回复的用户内容 4=>问答冻结  5=>问答解冻
     *          'gid' => 问答问题ID  仅存问题ID
     *          'proportion' => 问答问题收益比例
     *          'question_type' => 1=>星盘 2=>骰子 3=>塔罗
     *          'task_id' => 任务ID
     *          'team_id' => 团队ID
     *      ]
     * @return bool
     */
    public function astrZyhsQuestionAnswerEarningsSend(array $data)
    {
        try
        {
            // 获取占星师账户信息
            $astrAccountInfo = $this->getAstrAccountInfo($data['astr_id']);
            // 需要更新的占星师账户信息
            $accountData = [
                'balance' => (float)sprintf("%.2f", $astrAccountInfo['balance'] + $data['earning']),
                'total_amount' => (float)sprintf("%.2f", $astrAccountInfo['total_amount'] + $data['earning']),
                'update_time' => time(),
            ];
            Log::write('占星师账户 准有好事-问答 流水发放；发放前账户信息：' . json_encode($astrAccountInfo, JSON_UNESCAPED_UNICODE) . ';预更新信息' . json_encode($accountData, JSON_UNESCAPED_UNICODE), 'log', true);
            // 更新占星师账户信息
            // 占星师回复 更新占星师账户信息
            $this->updateData((int)$astrAccountInfo['id'], $data['astr_id'], $accountData);
            // 新增占星师能力值 1点    占星师行为=>占星师每完成一单，能力分+1
            // 新增占星师账户记录
            $accountRecord = [
                'astr_id' => $data['astr_id'],
                'type' => (int)$data['type'],
                'gid' => $data['gid'],
                'qid' => $data['task_id'],
                'good_amount' => $data['total_amount'],
                'proportion' => $data['proportion'],
                'question_type' => 4,   // 1=>定制报告 2=>问答 3=>连线咨询 4=>准有好事-问答
                'amount' => $data['earning'],
                'balance' => $accountData['balance'],
                'create_time' => $accountData['update_time'],
                'team_id' => $data['team_id'],
            ];
            (new ZlcrAstrAccountRecord())->addRecord($data['astr_id'], $accountRecord);
        }
        catch (\Exception $e)
        {
            Log::write('占星师 问答 收益发放，错误信息:' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error');
            return false;
        }
        return true;
    }

    /**
     * RTC 连线咨询 收益发放
     * @param array $data
     *      [
     *          'earning' => 本单收益，扣除手续费及营业税费
     *          'total_amount' => 本单用户实际支付总金额 问题金额+所有追问支付金额（有效，取消的不算在内）
     *          'astr_id' => 占星师ID
     *          'type' => 1=>入账 2=>提现 3=>后台人员回复的用户内容 4=>问答冻结  5=>问答解冻
     *          'gid' => 问答问题ID  仅存问题ID
     *          'proportion' => 问答问题收益比例
     *          'team_id' => 团队ID
     *      ]
     * @param int $appType 1=>准有好事  2=>准了APP
     * @return bool
     */
    public function astrGiftEarningsSend(array $data, int $appType = 1)
    {
        try
        {
            // 获取占星师账户信息
            $astrAccountInfo = $this->getAstrAccountInfo($data['astr_id']);
            // 需要更新的占星师账户信息
            $accountData = [
                'balance' => (float)sprintf("%.2f", $astrAccountInfo['balance'] + $data['earning']),
                'total_amount' => (float)sprintf("%.2f", $astrAccountInfo['total_amount'] + $data['earning']),
                'update_time' => time(),
            ];
            // 占星师回复 更新占星师账户信息
            $this->updateData((int)$astrAccountInfo['id'], $data['astr_id'], $accountData);
            // 新增占星师账户记录
            $accountRecord = [
                'astr_id' => $data['astr_id'],
                'type' => (int)$data['type'],
                'gid' => $data['gid'],
                'qid' => 0,
                'good_amount' => $data['total_amount'],
                'proportion' => $data['proportion'],
                'question_type' => $appType === 1 ? 7 : 6,   // 1=>定制报告 2=>问答 3=>准有好事-连线咨询 4=>准有好事-问答 5=>准了-连线咨询 6=>准了- 连线咨询 打赏 7=>准有好事 - 连线咨询 打赏
                'amount' => $data['earning'],
                'balance' => $accountData['balance'],
                'create_time' => $accountData['update_time'],
                'team_id' => $data['team_id'],
            ];
            (new ZlcrAstrAccountRecord())->addRecord($data['astr_id'], $accountRecord);
        }
        catch (\Exception $e)
        {
            Log::write('占星师 连线咨询打赏礼物 收益发放，错误信息:' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error');
            return false;
        }
        return true;
    }
}
